package com.liu.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.liu.entity.LiuLoginUser;
import com.liu.entity.LiuUser;
import com.liu.service.LiuUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.List;

/**
 * @ClassName IndexController
 * @Author liuxin
 * @Date Created in 2023-01-13 23:00
 * @Version 1.0
 */

@RestController
@Slf4j
public class IndexController {

    @Resource
    private LiuUserService liuUserService;

    @PostMapping("login")
    public ResponseEntity<LiuLoginUser> login(@RequestBody
                                                  @Validated LiuUser liuUser, BindingResult bindingResult){
        //1.处理不合法的数据
        List<ObjectError> allErrors = bindingResult.getAllErrors();
        allErrors.forEach(error ->log.error("登录时用户校验失败：{}",error.getDefaultMessage()));
        if(allErrors.size() > 0){
            return ResponseEntity.status(501).build();
        }
        //2.执行登录逻辑

        LiuLoginUser login = null;
        try {
            login = liuUserService.login(liuUser.getUserName(), liuUser.getPassword());
        } catch (JsonProcessingException e) {

            e.printStackTrace();
            return ResponseEntity.status(502).body(login);
        }
        return ResponseEntity.ok().body(login);
    }
    @GetMapping ("logout")
    public ResponseEntity<String> logout(){

        try {
             liuUserService.logout();
        } catch (Exception e) {

            e.printStackTrace();
            return ResponseEntity.status(503).build();
        }
        return ResponseEntity.ok().body("退出成功");
    }
}
